﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Sale_NewSaleOrder : System.Web.UI.Page
{
    DataTable dt;
    protected Mode EditMode;
    protected int OrderID;
    protected int EditRowIdx = -1;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (null != Request.QueryString["OrderID"])
            {
                string ordernumber, customername, salername, comment;
                decimal sum;
                DateTime orderdate;
                OrderID = int.Parse(Request.QueryString["OrderID"]);
                SaleOrderBL.GetOrderbyID(OrderID,out dt,out ordernumber,out customername, out sum,out orderdate,out salername,out comment);
                TextBoxNumber.Text = ordernumber;
                TextBoxCustomer.Text = customername;
                TextBoxSum.Text = sum.ToString();
                TextBoxDate.Text = orderdate.ToString("yyyy-MM-dd");
                TextBoxSaler.Text = salername;
                TextBoxComment.Text = comment; 
            }
            else
            {
                OrderID = 0;
                dt = SaleOrderBL.GetEmptyList();
                TextBoxSum.Text = "0";
            }
            EditMode = Mode.Empty;
            ShowData();
            ViewState["OrderID"] = OrderID;
            ViewState["DataSource"] = dt;
            ViewState["Mode"] = EditMode;

            SetButtonbyMode(EditMode);
        }
        else
        {
            OrderID = (int)ViewState["OrderID"] ;
            dt = (DataTable)ViewState["DataSource"] ;
            EditMode =(Mode) ViewState["Mode"] ;
            if (Mode.Edit == EditMode)
            {
                EditRowIdx = (int)ViewState["EditRowIdx"];
            }
        }
    }

    void ShowData()
    {
        string[] keys = { "ProductID" };
        //show the general information

        //show the detail informations
        GridViewDetail.DataSource = dt;
        GridViewDetail.DataKeyNames = keys;
        GridViewDetail.DataBind();
    }

    protected void GridViewDetail_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index;
        if ("DeleteItem" == e.CommandName)
        {
            index = PublicDefine.GetSelectRowIndex(e);
            EditMode = Mode.Empty;
            ViewState["Mode"] = EditMode;
            //enable item edit
            SetButtonbyMode(EditMode);
            //delete the selected row
            dt.Rows.Remove(dt.Rows[index]);
            ShowData();
        }
        if ("EditItem" == e.CommandName)
        {
            index = PublicDefine.GetSelectRowIndex(e);
            EditMode = Mode.Edit;
            ViewState["Mode"] = EditMode;
            EditRowIdx = index;
            ViewState["EditRowIdx"] = EditRowIdx;
            //enable item edit
            SetButtonbyMode(EditMode);
            //set textbox
            HiddenFieldProductID.Value = dt.Rows[index]["ProductID"].ToString();
            TextBoxProductCode.Text = dt.Rows[index]["ProductCode"].ToString();
            TextBoxItemNumber.Text = dt.Rows[index]["Quantity"].ToString();
            TextBoxItemPrice.Text = dt.Rows[index]["Price"].ToString();
        }
    }

    protected void ButtonAddNewRow_Click(object sender, EventArgs e)
    {
        EditMode = Mode.AddNew;
        ViewState["Mode"] = EditMode;
        ClearItemEditRegion();
        //enable item edit
        SetButtonbyMode(EditMode);
    }

    protected void ButtonItemSave_Click(object sender, EventArgs e)
    {
        SaveItem();
        ViewState["DataSource"] = dt;
        EditMode = Mode.Empty;
        ViewState["Mode"] = EditMode;
        SetButtonbyMode(EditMode);
        ClearItemEditRegion();
        ShowData();
    }

    protected void ButtonItemSaveandNew_Click(object sender, EventArgs e)
    {
        SaveItem();
        ViewState["DataSource"] = dt;
        EditMode = Mode.AddNew;
        ViewState["Mode"] = EditMode;
        SetButtonbyMode(EditMode);
        ClearItemEditRegion();
        ShowData();
    }

    void SetButtonbyMode(Mode mode)
    {
        if (Mode.Empty == mode)
        {
            ButtonItemSaveandNew.Enabled = false;
            ButtonItemSave.Enabled = false;
            ButtonItemCancel.Enabled = false;
        }
        else
        {
            ButtonItemSaveandNew.Enabled = true;
            ButtonItemSave.Enabled = true;
            ButtonItemCancel.Enabled = true;
        }
    }

    void ClearItemEditRegion()
    {
        this.HiddenFieldProductID.Value = string.Empty;
        this.TextBoxProductCode.Text = string.Empty;
        this.TextBoxItemPrice.Text = string.Empty;
        this.TextBoxItemNumber.Text = string.Empty;
    }

    void SaveItem()
    {
        LabelError.Text = "";
        int productid;
        string productname, productmodule, productcolor, productcode;
        productcode = TextBoxProductCode.Text.Trim();
        SystemFunction.GetProductInfo(productcode, out productid, out productname, out productmodule, out productcolor);
        if (productid > 0)
        {
            HiddenFieldProductID.Value = productid.ToString();
        }
        else
        {
            LabelError.Text = "没有找到这个产品编码对应的产品！";
            return;
        }
        decimal price = 0;
        try
        {
            price = decimal.Parse(TextBoxItemPrice.Text.Trim());
        }
        catch
        {
            LabelError.Text = "价格不合法！";
            return;
        }
        decimal quantity = 0;
        try
        {
            quantity = decimal.Parse(TextBoxItemNumber.Text.Trim());
        }
        catch
        {
            LabelError.Text = "数量不合法！";
            return;
        }

        DataRow dr = SaleOrderBL.AddNewRow(dt,productid, productcode, productname, productmodule, productcolor, price, quantity);
        if (Mode.AddNew == EditMode)
        {
            dt.Rows.Add(dr);
            ViewState["EditRowIdx"] = dt.Rows.Count - 1;
        }
        else if (Mode.Edit == EditMode)
        {
            dt = SystemFunction.ReplaceRow(dt, dr, EditRowIdx);
            ViewState["EditRowIdx"] = EditRowIdx;
        }

        TextBoxSum.Text = GetSum(dt).ToString();
    }    

    decimal GetSum(DataTable dt)
    {
        decimal sum = 0;
        foreach (DataRow dr in dt.Rows)
        {
            decimal quantity = (decimal)dr["Quantity"];
            decimal price = (decimal)dr["Price"];
            sum += quantity * price;
        }
        return sum;
    }

    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        if (CheckOrderData())
        {
            DateTime date = DateTime.Parse(TextBoxDate.Text.Trim());
            string num = TextBoxNumber.Text.Trim();
            string customer = TextBoxCustomer.Text.Trim();
            decimal sum = decimal.Parse(TextBoxSum.Text.Trim());
            string saler = TextBoxSaler.Text.Trim();
            string comment = TextBoxComment.Text.Trim();
            int oldid = OrderID;
            SaleOrderBL.SaveOrder(oldid, dt, num, customer, sum, date, saler, comment, out OrderID);

            ViewState["OrderID"] = OrderID;
            EditMode = Mode.Empty;
            ViewState["Mode"] = EditMode;

            SetButtonbyMode(EditMode);
        }

    }

    bool CheckOrderData()
    {
        bool result = false;
        DateTime date;

        LabelError.Text = "";
        try
        {
            date = DateTime.Parse(TextBoxDate.Text.Trim());
        }
        catch
        {
            LabelError.Text = "时间不合法";
            return result;
        }
        if (TextBoxNumber.Text.Trim().Length > 60)
        {
            LabelError.Text = "合同号不能大于60个字符";
            return result;
        }
        if (0 == TextBoxNumber.Text.Trim().Length)
        {
            LabelError.Text = "合同号不能为空";
            return result;
        }
        if (TextBoxCustomer.Text.Trim().Length > 10)
        {
            LabelError.Text = "客户名不能多于5个字";
            return result;
        }
        if (0 == TextBoxCustomer.Text.Trim().Length)
        {
            LabelError.Text = "客户名不能为空";
            return result;
        }
        if (TextBoxSaler.Text.Trim().Length > 10)
        {
            LabelError.Text = "销售人员不能多于5个字";
            return result;
        }
        if (0 == TextBoxSaler.Text.Trim().Length)
        {
            LabelError.Text = "销售人员不能为空";
            return result;
        }
        if (TextBoxComment.Text.Trim().Length > 400)
        {
            LabelError.Text = "备注不能多于200个字";
            return result;
        }
        if (0 == dt.Rows.Count)
        {
            LabelError.Text = "没有明细项！";
            return result;
        }
        return true;
    }



    protected void ButtonCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewSales.aspx");
    }
}
